package com.kizitonwose.calendarview.ui;

import ohos.agp.components.Component;
import ohos.agp.components.DirectionalLayout;

import com.kizitonwose.calendarview.model.CalendarDay;

import java.util.List;

public class WeekHolder {
    private List<DayHolder> dayHolders;
    private DirectionalLayout container;

    public WeekHolder(List<DayHolder> dayHolders) {
        this.dayHolders = dayHolders;
    }

    Component inflateWeekView(DirectionalLayout parent) {

        container = new DirectionalLayout(parent.getContext());
        DirectionalLayout.LayoutConfig layoutConfig = new DirectionalLayout.LayoutConfig();
        layoutConfig.width = DirectionalLayout.LayoutConfig.MATCH_CONTENT;
        layoutConfig.height = DirectionalLayout.LayoutConfig.MATCH_CONTENT;
        container.setLayoutConfig(layoutConfig);
        container.setOrientation(DirectionalLayout.HORIZONTAL);
        //container.setTotalWeight((float) dayHolders.size());
        for (DayHolder dayHolder : dayHolders) {
            container.addComponent(dayHolder.inflateDayView(container));
        }
        return container;
    }

    public void bindWeekView(List<CalendarDay> daysOfWeek) {
        if (daysOfWeek == null || daysOfWeek.isEmpty()) {
            //隐藏
            container.setVisibility(Component.HIDE);
        } else {
            //否则显示，必须设置否则导致某行数据缺失
            container.setVisibility(Component.VISIBLE);
        }
        //布局变化了需进行刷新重绘（否则每个月的星期行数不同时，高度无法恢复，会使用上一个component的缓存高度）
        container.invalidate();

        int size = dayHolders.size();
        for (int index = 0; index < size; index++) {
            DayHolder dayHolder = dayHolders.get(index);
            if (daysOfWeek != null && index < daysOfWeek.size()) {
                dayHolder.bindDayView(daysOfWeek.get(index));
            } else {
                dayHolder.bindDayView(null);
            }
        }
    }

    public boolean reloadDay(CalendarDay day) {
        for (DayHolder dayHolder : dayHolders) {
            if (dayHolder.reloadViewIfNecessary(day)) {
                return true;
            }
        }
        return false;
    }
}
